var util = require('../../../utils/util.js');
var api = require('../../../config/api.js');
const pay = require('../../../services/pay.js');

var app = getApp();
var isPay = 0;

Page({
  data: {
    productStockId: '',     //购买的商品规格ID
    quantity: 0,            //购买的数量
    checkedAddress: {},     //选择的地址
    checkedCoupon: [],      //选择的优惠券
    couponList: [],         //优惠券列表
    goodsTotalPrice: 0.00,  //商品总价
    freightPrice: 0.00,     //快递费
    couponPrice: 0.00,      //优惠券抵扣金额
    orderTotalPrice: 0.00,  //订单总价
    actualPrice: 0.00,      //实际需要支付的总价
    addressId: 0,           //选择的地址ID
    couponId: 0,            //选择的优惠券ID
    wxPayChecked: true,     //是否需要微信支付
    balanceChecked: false,  //是否选择余额支付
    pointChecked: false,    //是否选择积分支付
    balancePay: 0.00,       //余额支付金额
    balancePayMemo: '',     //余额支付描述
    pointPay: 0,            //积分抵扣积分
    pointPayMemo: '',       //积分抵扣描述
    pointOffset: 0.00,      //积分抵扣金额
    memberBalance: 0.00,    //会员余额
    memberPoint: 0,         //会员积分
    memberId: 0 ,           //会员ID
    memo: '' ,              //买家留言
    boxShow: false,         //积分输入框
    openCoupons: false,     //优惠券选择框
    pointValue: '',         //会员自己输入的积分值
    pointButton: true,      //是否显示积分确认按钮
    pointRatio: 50,          //积分抵扣比例 
    codChecked: false,
    payType: "0"
  },
  onLoad: function (options) {
		var isPointPay = options.isPointPay;
    this.setData({
			isPointPay: isPointPay,
      productStockId: options.productStockId,
      quantity: options.quantity,
      price: options.price,
      imgUrl: options.imgUrl,
      name: options.name,
      subName: options.subName,
      specName: options.specName,
      content: options.memo,
      groupId: options.groupId
    });
    this.getdefaultAddress();
    this.getMemberInfo();
    // this.getCouponList();
  },
  onShow: function () {
    var checkedAddress = app.globalData.checkedAddress;
    if (checkedAddress != null) {
      this.setData({
        checkedAddress: checkedAddress,
        addressId: checkedAddress.id
      });
    } else {
      this.setData({
        checkedAddress: {},
        addressId: 0
      });
    }
    this.getCheckoutInfo();
  },
  //打开选择优惠券弹窗
  selectCoupons: function () {
    this.setData({
      openCoupons: true
    });
  },
  //关闭选择优惠券弹窗
  closeSelectCoupons: function () {
    this.setData({
      openCoupons: false
    });
  },
  //选择优惠券
  chooseCoupon: function (event) {
    var index = event.currentTarget.dataset.index;
    var couponList = this.data.couponList;
    for (var i = 0; i < couponList.length; i++) {
      couponList[i].choose = false;    
    }
    couponList[index].choose = true;
    var couponId = event.currentTarget.dataset.couponId;
    this.setData({
      couponId: couponId,
      couponList: couponList
    })
    this.getCheckoutInfo();
  },
  getCouponList: function () {
    var that = this;
    let cartItemIds = this.data.checkedGoodsList.filter(function (element, index, array) {
      if (element.checked == true) {
        return true;
      } else {
        return false;
      }
    });
    cartItemIds = cartItemIds.map(function (element, index, array) {
      if (element.checked == true) {
        return element.id;
      }
    });
    var data = {
      cartItemIds: cartItemIds
    }
    util.request(api.CouponChecked, data, 'POST').then(function (data) {
      if (data.type === 'success') {
        that.setData({
          couponList: data.data.couponList
        });
      } else {
        console.log(data.content);
      }
    });
  },
  getMemberInfo: function () {
    var that = this;
    util.request(api.MemberInfoUrl, {}, 'GET').then(function (data) {
      if (data.type === 'success') {
        that.setData({
          memberId: data.data.member.id,
          memberBalance: data.data.member.balance,
          memberPoint: data.data.member.point,
          pointRatio: data.data.pointRatio
        });
      } else {
        console.log(data.content);
      }
    });
  },
  pointConfirm: function () {
    this.getCheckoutInfo();
  },
  pointValueInput: function (event) {
    var pointValue = event.detail.value;
    this.setData({
      pointValue: pointValue
    });
    if (pointValue != null && pointValue != '') {
      this.setData({
        pointButton: false
      });
    } else {
      this.setData({
        pointButton: true
      });
    }
  },
  balanceChange: function (event) {
    //货到付款不允许使用余额支付
    if (this.data.payType == "1") {
      this.setData({
        balanceChecked: false
      });
      return false;
    }
    this.setData({
      balanceChecked: event.detail.value
    });
    this.getCheckoutInfo();
  },
  pointChange: function (event) {

    //货到付款不允许使用积分
    if (this.data.payType == "1") {
      this.setData({
        pointChecked: false
      });
      return false;
    }

    var pointRatio = this.data.pointRatio;
    var memberPoint = this.data.memberPoint;
    if (memberPoint < pointRatio) {
      util.showErrorToast('积分不足');
      this.setData({
        pointChecked: false
      });
      return false;
    }
    var pointChecked = event.detail.value;
    this.setData({
      pointChecked: pointChecked
    });
    if (pointChecked) {
      this.setData({
        boxShow: true
      });
    } else {
      this.setData({
        boxShow: false,
        pointValue: '',
        pointButton: true
      });
    }
    this.getCheckoutInfo();
  },

  switchPay: function (event) {
    var type = event.currentTarget.dataset.type;
    this.setData({
      "payType": type
    });
    if (type == "0") {

      this.setData({
        "wxPayChecked": true,
        "codChecked": false,
      });
      this.getCheckoutInfo();
    } else if (type == "1") {
      this.setData({
        "wxPayChecked": false,
        "codChecked": true,

        balanceChecked: false,
        balancePayMemo: '',

        pointChecked: false,
        pointValue: '',
        pointPayMemo: ''
      });
      this.getCheckoutInfo();
    }

  },
  
  memoInput: function (event) {
    this.setData({
      memo: event.detail.value
    });
  },
  getdefaultAddress: function () {
    var that = this;
    //查询默认地址
    util.request(api.AddressDefault, {}, 'POST').then(function (data) {
      if (data.type == 'success') {
        if (data.data.receiver != null) {
          that.setData({
            checkedAddress: data.data.receiver,
            addressId: data.data.receiver.id
          });
          app.globalData.checkedAddress = data.data.receiver;
        }       
      } else {
        console.log(data.content);
      }
    });
  },
  getCheckoutInfo: function () {
    isPay == 1;
    let that = this;
    let productStockId = that.data.productStockId;
    let quantity = that.data.quantity;
    let price = that.data.price;
    var data = {
      addressId: that.data.addressId,
      couponId: that.data.couponId,
      productStockId: productStockId,
      quantity: quantity,
      price: price,
      balanceChecked: that.data.balanceChecked,
      pointChecked: that.data.pointChecked,
      pointValue: that.data.pointValue,
      payType: that.data.payType
    }
    util.request(api.GroupingOrderInfo, data, 'POST').then(function (data) {
      if (data.type == 'success') {
        that.setData({
          goodsTotalPrice: data.data.goodsTotalPrice,   //商品合计金额
          freightPrice: data.data.freightPrice,         //运费
          balancePay: data.data.balancePay,             //余额支付金额
          balancePayMemo: data.data.balancePayMemo,     //余额支付描述
          pointPay: data.data.pointPay,                 //积分抵扣积分
          pointPayMemo: data.data.pointPayMemo,         //积分抵扣描述
          pointOffset: data.data.pointOffset,           //积分抵扣金额
          couponPrice: data.data.couponPrice,           //优惠券抵扣金额
          actualPrice: data.data.actualPrice,           //实际支付金额
          wxPayChecked: data.data.wxPayChecked,         //是否需要微信支付
          pointChecked: data.data.pointChecked,         //是否需要积分支付
          balanceChecked: data.data.balanceChecked      //是否需要余额支付
        });
        isPay = 0;
      } else {
        util.showErrorToast(data.content);
        isPay = 0;
      }
    });
  },
  selectAddress() {
    wx.navigateTo({
      url: '/pages/shopping/address/address',
    })
  },
  submitOrder: function () {
    if (isPay == 1) {
      return false;
    }
    isPay = 1;
    var that = this;
    if (that.data.addressId <= 0) {
      util.showErrorToast('请选择收货地址');
      return false;
    }
    wx.showModal({
      title: '提示',
      content: '确定结算下单吗',
      success: function (res) {
        if (res.confirm) {
          let productStockId = that.data.productStockId;
          let quantity = that.data.quantity;
          let price = that.data.price;
          let groupId = that.data.groupId;
          var data = {
            addressId: that.data.addressId,
            couponId: that.data.couponId,
            productStockId: productStockId,
            quantity: quantity,
            price: price,
            groupId: groupId,
            actualPrice: that.data.actualPrice,
            pointOffset: that.data.pointOffset,
            couponPrice: that.data.couponPrice,
            balancePay: that.data.balancePay,
            pointPay: that.data.pointPay,
            memo: that.data.memo,
            payType: that.data.payType
          }
          util.request(api.GroupingOrderSubmit, data, 'POST').then(function (data) {
            if (data.type == 'success') {
              const orderId = data.data.orderId;
              const isPay = data.data.isPay;
              if (isPay == 0) {
                var data = {
                  orderId: orderId
                }
                util.request(api.PayPrepayId, data, 'POST').then(function (res) {
                  wx.requestPayment({
                    timeStamp: res.timeStamp,
                    nonceStr: res.nonceStr,
                    package: res.package,
                    signType: res.signType,
                    paySign: res.paySign,
                    success: function (res) {
                      util.showSuccessToast('订单支付成功');
                      setTimeout(function () {
                        wx.redirectTo({
                          url: '/pages/ucenter/order/order?id=0'
                        })
                      }, 1500)
                    },
                    fail: function (res) {
                      util.showErrorToast('订单未支付');
                      setTimeout(function () {
                        wx.redirectTo({
                          url: '/pages/ucenter/order/order?id=0'
                        })
                      }, 1500)
                    }
                  })
                })
              } else {
                wx.redirectTo({
                  url: '/pages/ucenter/order/order?id=0'
                })
              }
            } else {
              util.showErrorToast(data.content);
              isPay = 0;
            }
          });
        } else if (res.cancel) {
          isPay = 0;
        }
      }
    })
  }

})